<?php
/**
 * This file is form http://findcat.cn
 *
 * @link     https://findcat.cn
 * @email    1476982312@qq.com
 */
namespace Database\Seeder;

use Encore\Admin\Auth\Database\Menu;
use Encore\Admin\Auth\Database\Role;
use Encore\Admin\Auth\Database\Permission;

/**
 * 生成角色的seeder基础方法.
 *
 * Trait MenuSeederMaker
 */
trait RoleSeederMaker
{
    /**
     * 创建角色.
     *
     * @param $name
     * @param $slug
     * @param $permissionSlug
     * @param mixed $menuUri
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    protected function createRoles($name, $slug, $permissionSlug, $menuUri)
    {
        $role = Role::query()->updateOrCreate(
            [
                'name' => $name,
                'slug' => $slug,
            ]
        );

        Permission::query()
            ->whereIn('slug', $permissionSlug)
            ->get()
            ->map(function ($permission) use ($role) {
                $role->permissions()->save($permission);
            });

        Menu::query()
            ->whereIn('uri', $menuUri)
            ->get()
            ->map(function ($menu) use ($role) {
                $role->menus()->save($menu);
            });

        return $role;
    }
}
